package com.icinfo.cloud.provider.common.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 对接市监一体化平台单点的登录加密算法
 *
 * @author 谭必靖
 * @date 2020-12-15
 **/
public class EpsoftStringUtil {


    //实例化密钥
    private static Key key;

    //原始密钥
    //private static String KEY_STR = "my-springmvc-2019-04-17";
    private static String KEY_STR = "epsoft.comdslkadsjdsaljdadasdjcf20201215";

    //编码
    private static String CHARSETNAME = "UTF-8";

    //密钥算法
    private static String KEY_ALGORITHM = "AES";

    //加密-解密算法 / 工作模式 / 填充方式
    private static String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * 初始化key
     */
    static {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(KEY_STR.getBytes());
            kgen.init(128, random);
            key = kgen.generateKey();
            kgen = null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getEncryptString(String str) {
        try {
            byte[] bytes = str.getBytes(CHARSETNAME);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return Base64.getEncoder().encodeToString(doFinal);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @description: 对AES加密字符串进行解密
     * @param str
     * @return
     */
    public static String getDecryptString(String str) {
        try {
            byte[] bytes = Base64.getDecoder().decode(str);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return new String(doFinal, CHARSETNAME);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        String password = "13588012414";
        String pass = EpsoftStringUtil.getEncryptString(password);
        System.out.println("加密："+pass);
        System.out.println("解密："+ EpsoftStringUtil.getDecryptString(pass));

    }
}
